// pages/my/orders/index.js
const app = getApp()
const { baseURL } = require('../../../fetch/http')
const api = require('../../../fetch/api')
Page({
  /**
   * 页面的初始数据
   */
  data: { 
    baseURL: baseURL,
    tabs: ['全部','待付款','待发货','待收货','已完成'],
    tabIndex: 0,
    toView: 's0',
    arr: [],
    loading: false,
    finished: false,
    page: 1
  },
  switchTab(e) {
    const {
      index
    } = app.dataSet(e)
    if (this.data.tabIndex != index) {
      this.setData({
        tabIndex: index,
        toView: 's' + index
      })
      this.clear()
      this.orderList()
    }
  },
  async orderList() {
    if (!this.data.loading) {
      this.setData({
        loading: true
      })
      let res = await api.orderList({
        page: this.data.page,
        state: this.data.tabIndex
      })
      let finished = false
      res.data.length == 0 && (finished = true)
      this.setData({
        arr:res.data,
        finished,
        loading: false
      })
    }
  },
  orderDetail(e) {
    const { id } = app.dataSet(e)
    wx.navigateTo({
      url: '/pages/my/orderDetail/index?id=' + id,
    })
  },
  clear() {
    this.setData({
      arr: [],
      page: 1,
      loading: false,
      finished: false
    })
  },
  async cancelOrder(e) {
    const { id, index } = app.dataSet(e)
    let res = await api.cancelOrder({
      order_id: id
    })
    let arr = [...this.data.arr]
    arr.splice(index,1)
    this.setData({
      arr
    })
  },
  async pay(e) {
    const { index, id } = app.dataSet(e)
    let res = await api.orderPay({
      order_id: id
    })
    api.wxpay(res.data).then(res => {
      if (res.errMsg == "requestPayment:ok") {
        app.toast('支付成功','success',()=>{
          // this.clear()
          // this.orderDetail()
          this.orderList()
        })
      }
    }).catch(error => {
      console.log(error);
    })
  },
  async remove(e) {
    const { id, index } = app.dataSet(e)
    let res = await api.cancelOrder({
      order_id: id
    })
    let arr = [...this.data.arr]
    arr.splice(index,1)
    this.setData({
      arr
    })
  },
  async sign(e) {
    const { index, id } = app.dataSet(e)
    let res = await api.signFor({
      order_id: id
    })
    console.log(res)
    if(res.code==200){
      this.setData({
        page:1
      })
      this.orderList()
    }

    // this.orderDetail()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
  
   
    this.orderList()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})